﻿"use strict";
//var ApiServer = "http://www.$lvl.com/gas/";
var LApp = angular.module('LApp', ['leaflet-directive', 'ngLv']);

LApp.controller('RescueControl', function ($scope, $compile, $timeout, $interval, leafletData, leafletHelpers, $lvl) {
    //$("body").css({
    //    height: document.documentElement.clientHeight + "px",
    //    width: document.documentElement.clientWidth + "px"
    //})

    var _user = $lvl.storeItem("CurrentUser");
    window.AccessToken = _user.Token;


    angular.extend($scope, {
        BodyHeight:document.documentElement.clientHeight,
        SelTask: null,
        taskList: {},
        SetTaskTextClass: function (item) {
            switch (item.TaskState) {
                case 0:
                    return "text-warning";
                case 1:
                    return "text-primary";
                case 2:
                    return "text-muted";
                case 3:
                    return "text-info";
                case 4:
                    return "text-warning";
                case 5:
                    return "text-success";
                default:
            }
            return "text-warning";
        },
        TaskItemClick: function (item) {
            if ($scope.SelTask && $scope.SelTask.TaskNo == item.TaskNo) {

                $scope.SelTask = null;

                $scope.addTaskMarkersToMap();
                $scope.Map.resetView();//二次点击会出错
            } else {

                $scope.SelTask = item;
                $scope.SelTask.NewContent = '';
                $scope.focusTaskMarker(item.TaskNo);
            }
        },
        MessagePanelSroll: function () {
            var aa = document.querySelector('.msgContentWindow');

            var ss = angular.element(document).find('.msgContentWindow');
            aa.scrollTop = aa.scrollHeight;
        },
        SendMessage: function () {
            if (!$scope.SelTask.NewContent) {
                $scope.SelTask.NewContent = '';
                return;
            }
            $lvl.ajax({
                url:GlobalConfig.APIServer+ 'api/keepsys/task/msgadd',
                method: 'POST',
                data: {
                    TaskNo: $scope.SelTask.TaskNo,
                    MsgType: 'text',
                    MsgContent: $scope.SelTask.NewContent,
                    FromPlatform: 1
                },
                success: function (response) {
                    //$scope.SelTask.MsgList.push(response.result);
                    //$scope.MessagePanelSroll();

                    //$scope.SelTask.NewContent = '';
                }
            })


            $scope.SelTask.MsgList.push({
                MsgType: "text",
                FromPlatform: 1,
                MsgContent: $scope.SelTask.NewContent
            })

            //$scope.MessagePanelSroll();

            $scope.SelTask.NewContent = '';


        },
        SendMessageKeyUp: function (e) {
            var keycode = window.event ? e.keyCode : e.which;
            if (keycode == 13) {
                $scope.SendMessage();
            }
        },
        DealTask_1: function (taskinfo) {
            $lvl.ajax({
                url: GlobalConfig.APIServer + 'api/keepsys/task/deal',
                method: 'GET',
                data: {
                    TaskNo: taskinfo.TaskNo,
                    type: 1
                },
                success: function (response) {
                    //$scope.SelTask.MsgList.push(response.result);
                    //$scope.MessagePanelSroll();

                    //$scope.SelTask.NewContent = '';
                }
            })
        },
        DealTask_2: function (taskinfo) {
            $lvl.ajax({
                url: GlobalConfig.APIServer + 'api/keepsys/task/deal',
                method: 'GET',
                data: {
                    TaskNo: taskinfo.TaskNo,
                    type: 2,
                    drayId: $scope.SelectDrayUser
                },
                success: function (response) {
                    //$scope.SelTask.MsgList.push(response.result);
                    //$scope.MessagePanelSroll();

                    //$scope.SelTask.NewContent = '';
                }
            })
        },
        DealTask_3: function (taskinfo) {
            $lvl.ajax({
                url: GlobalConfig.APIServer + 'api/keepsys/task/deal',
                method: 'GET',
                data: {
                    TaskNo: taskinfo.TaskNo,
                    type: 5
                },
                success: function (response) {
                    //$scope.SelTask.MsgList.push(response.result);
                    //$scope.MessagePanelSroll();

                    //$scope.SelTask.NewContent = '';
                }
            })
        }
    })

    angular.extend($scope, {
        map: {
            center: {
                lng: 118.79585,
                lat: 32.03762,
                zoom: 13,
            },
            defaults: {
                maxZoom: 18,
                minZoom: 1,
                tileLayer: 'http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
                tileLayerOptions: {
                    subdomains: '1234'
                },
                attributionControl: false,
                zoomControl: false
            },
            markers: {
                //aaa: {
                //    firstMarker: {
                //        lng: 118.79585,
                //        lat: 32.03762,
                //        message: "I want to travel here!",
                //        focus: false,
                //        draggable: true
                //    }
                //}
            }
        },
        addTaskMarkersToMap: function () {
            angular.forEach($scope.taskList, function (a, i) {
                var _html = '<div style="width:400px;">'
                        + '<div class="row">'
                            + '<div class="col-md-4">'
                                + '<img style="width:130px;" class="img-responsive" ng-src="{{SelTask.CarInfo.CarFaceImgUrl}}" />'
                            + '</div>'
                            + '<div class="col-md-8">'
                                + '<div><label>车主：</label> {{SelTask.UserInfo.FullName}}</div>'
                                + '<div><label>车号：</label> {{SelTask.CarInfo.CarNo}}</div>'
                                + '<div><label>品牌：</label> {{SelTask.CarInfo.CarBrandName}}</div>'
                                + '<div><label>车型：</label> {{SelTask.CarInfo.CarSeriesName}}</div>'
                                + '<div><label>车主手机：</label> {{SelTask.UserInfo.Mobile}}</div>'
                                + '<div><label>车辆位置：</label> {{SelTask.Address}}</div>'
                                + '<div><label>任务状态：</label>  {{SelTask.TaskStateDesc}}</div>'
                                + '<div ng-show="SelTask.TaskState==0"><label>任务操作：</label>  <a href="JavaScript:;" ng-click="DealTask_1(SelTask)">受理此任务</a></div>'
                                + '<div ng-show="SelTask.TaskState==1"><label>任务操作：</label><select ng-model="SelectDrayUser"><option ng-repeat="x in DrayDriverUserList" value="{{x.UserId}}">{{x.FullName}}</option></select>  <a href="JavaScript:;" ng-click="DealTask_2(SelTask)">调度车辆</a></div>'
                                //+ '<div ng-show="SelTask.TaskState==4"><label>任务操作：</label>  <a href="JavaScript:;" ng-click="DealTask_3(SelTask)">任务确认完成</a></div>'
                            + '</div>'
                        + '</div>'
                    + '</div>';

                $scope.map.markers["task_" + a.TaskNo] = {
                    lng: a.Lng,
                    lat: a.Lat,
                    label: { message: "李根华" },
                    popupOpen: function () { alert(111); },
                    message: _html,
                    popupOptions: { maxWidth: 1000 },
                    getMessageScope: function () { return $scope; },
                    icon: {
                        iconUrl: CONTENT_URL('Images/car1.png'),
                        iconSize: [64, 64], // size of the icon
                        iconAnchor: [35, 64], // point of the icon which will correspond to marker's location
                        popupAnchor: [-1, -36] // point from which the popup should open relative to the iconAnchor
                    }
                }
                
                if (a.DrayLng && a.DrayLat) {
                    $scope.map.markers["task_dray_" + a.TaskNo] = {
                        lng: a.DrayLng,
                        lat: a.DrayLat,
                       // message: _html,
                        popupOptions: { maxWidth: 1000 },
                        getMessageScope: function () { return $scope; },
                        icon: {
                            iconUrl: CONTENT_URL('Images/car2.png'),
                            iconSize: [32, 32], // size of the icon
                            iconAnchor: [10, 30], // point of the icon which will correspond to marker's location
                            popupAnchor: [-1, -36] // point from which the popup should open relative to the iconAnchor
                        }
                    }
                }
                
            })
           
        },

        focusTaskMarker: function (_TaskNo) {
            $scope.map.center.lng = $scope.map.markers["task_" + _TaskNo].lng;
            $scope.map.center.lat = $scope.map.markers["task_" + _TaskNo].lat;

            leafletData.getMarkers().$$state.value["task_" + _TaskNo].openPopup();
        }
    })

    angular.extend($scope, {
        //获取
        GetTaskList: function () {
            $lvl.ajax({
                url: GlobalConfig.APIServer + "api/keepsys/task/list",
                method:'GET',
                success: function (response) {
                    angular.forEach(response, function (a, i) {
                        var k = Convert_BD09_To_GCJ02(a.Lng, a.Lat);
                        a.Lng = k.lng;
                        a.Lat = k.lat;

                        if (a.DrayLng && a.DrayLat) {
                            var k1 = Convert_BD09_To_GCJ02(a.DrayLng, a.DrayLat);
                            a.DrayLng = k1.lng;
                            a.DrayLat = k1.lat;
                        }

                        $scope.taskList["task_" + i] = a;
                        if ($scope.SelTask && $scope.SelTask.TaskNo == a.TaskNo) {
                            var s = $scope.SelTask.NewContent;
                            $scope.SelTask = a;
                            $scope.SelTask.NewContent = s;
                        }
                    })
                    //$scope.taskList = response;


                    angular.forEach($scope.taskList, function (a, i) {

                        //a.MsgList = [{
                        //    MsgType: "text",
                        //    FromPlatform: 0,
                        //    MsgContent: "任务编号->"+a.TaskNo
                        //}, {
                        //    MsgType: "image",
                        //    FromPlatform: 0,
                        //    MsgContent: "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=215396445,585020023&fm=21&gp=0.jpg"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 1,
                        //    MsgContent: "很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务很高兴为你服务"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 1,
                        //    MsgContent: "很高兴为你服务"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 0,
                        //    MsgContent: "hahaha"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 0,
                        //    MsgContent: "我的车子坏了，需要你的帮助我的车子坏了，需要你的帮助我的车子坏了，需要你的帮助我的车子坏了，需要你的帮助我的车子坏了，需要你的帮助我的车子坏了，需要你的帮助我的车子坏了，需要你的帮助我的车子坏了，需要你的帮助我的车子坏了，需要你的帮助"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 0,
                        //    MsgContent: "hahaha"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 0,
                        //    MsgContent: "hahaha"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 0,
                        //    MsgContent: "hahaha"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 0,
                        //    MsgContent: "hahaha"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 0,
                        //    MsgContent: "hahaha"
                        //}, {
                        //    MsgType: "text",
                        //    FromPlatform: 0,
                        //    MsgContent: "hahaha"
                        //}]
                    })
                    $scope.addTaskMarkersToMap();

                }
            }, {hideloading:true})
        },
        //获取板车驾驶员列表
        GetDaryDriverUserList: function () {
            $lvl.ajax({
                url: GlobalConfig.APIServer + "api/keepsys/task/draylist",
                method: 'GET',
                success: function (response) {
                    $scope.DrayDriverUserList = response;
                    $scope.SelectDrayUser = response[0].UserId.toString();
                }
            }, { hideloading: true })
        }
    })

    //$scope.mapInit();
    $interval($scope.GetTaskList, 2000);
    //加载板车架驶员列表
    $scope.GetDaryDriverUserList();

    $scope.GetTaskList();
  
})




function Convert_BD09_To_GCJ02(lat, lng) {
    var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    var x = lng - 0.0065,
		y = lat - 0.006;

    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);

    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);

    return {
        lat: z * Math.cos(theta),
        lng: z * Math.sin(theta)
    }

}


